// pages/productDetail/productDetail.js
var app = getApp()
Page({
  data: {
    current: 0,
    cartList: [],
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    // console.log(options.id)
    var that = this;
    wx.request({
      url: app.globalData.allUrl + "/YMGW/superMarketAction/getSuperMarketEntrepot",
      data:
      {
        entrepotId: options.id
      },
      dataType: 'json',
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: {}, // 设置请求的 header
      success: function (res) {
       // console.log(res.data)
        that.setData({
          productDetails: res.data.SuperMarketEntrepot,
          Evaluates: res.data.Evaluates
        })
      },
    })
  },
  swichNav: function (e) {//点击切换样式
    var that = this;
    if (this.data.current === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        current: e.target.dataset.current
      })
    }
  },
  onReady: function (options) {
    // 页面渲染完成    
  },
  onShow: function () {
    // 页面显示
    if (wx.getStorageSync("cartLists").length > 0) {
      this.setData({
        cartList: wx.getStorageSync("cartLists")
      })
    }
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  sendMsgToBuy: function (e) {//获取用户所选中产品的详细信息
    var that = this;
    if (that.data.cartList.length > 0) {
      var config = false;
      for (var x in that.data.cartList) {
        if (that.data.cartList[x].productId == e.target.dataset.id) {
          if (that.data.cartList[x].quantity == that.data.cartList[x].repertory) {//如果增加的数量大于库存，则取消增加；
            wx.showToast({
              title: "库存不足",
              icon: "loading"
            })
          } else {
            that.data.cartList[x].quantity += 1;
          }
          config = true;
        }
      }
      if (!config) {

        getCartInfo(that, e)//加入购物车
      }
    } else {
     // console.log(this.data.cartList)
      getCartInfo(that, e)//加入购物车

    }

    wx.setStorageSync('cartLists', this.data.cartList)
    wx.navigateTo({
      url: '/pages/buy/buy',
    })
  },
})

function getCartInfo(that, e) {//加入购物车，将商品信息储存在
  //console.log(that.data.cartList)
  var CartName = e.target.dataset.name;
  var CartPrice = e.target.dataset.price;
  var CartID = e.target.dataset.id;
  var CartSuper = e.target.dataset.name;
  var Cartquantity = 1;
  var totalPrices = "";
  var Cartimg = e.target.dataset.img
  var Cartrepertory = e.target.dataset.repertory
  var carts = { productName: CartName, unitPrice: CartPrice, productId: CartID, quantity: Cartquantity, totalPrices: totalPrices, repertory: Cartrepertory, img: Cartimg }
  that.data.cartList.push(carts);
}